package com.spark.concurrency.other;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;

public class AtomicTest {
    public static void main(String[] args) {
        atomicReference();
        atomicInteger();
    }

    private static void atomicInteger() {
        AtomicInteger sum = new AtomicInteger();
        for (int i = 0; i < 100; i++) {
            new Thread(sum::getAndIncrement).start();
        }
        System.out.println(sum.get());
    }

    private static void atomicReference() {
        //使用CAS，解决线程安全的问题，
        AtomicReference<List<String>> ds = new AtomicReference<>();
        for (int i = 0; i < 100; i++) {
            new Thread(() -> {
                String date = LocalDateTime.now().format(DateTimeFormatter.ISO_DATE_TIME);
                //在金线程里这样在引用类型里增加不会有问题，
                ds.get().add(Thread.currentThread().getName() + ":" + date);
                System.out.println(Thread.currentThread().getName() + " Say:我准备好了，时间是：" + date);
            }
            ).start();
        }
        ds.get().forEach(System.out::println);
    }
}
